<template>
  <!-- 新建可视化窗口和重编辑窗口 -->
  <div>
    <a-modal
      :destroy-on-close="true"
      :visible="visible"
      :width="1140"
      :centered="true"
      ok-text="确定"
      cancel-text="取消"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div style="margin-top: -10px;">
        <span
          v-show="!titleModifiable"
          class="window-title"
          @click="setTitleModifiable"
          >{{
            currentGridItem && currentGridItem.chartOptions.title
              ? currentGridItem.chartOptions.title
              : title
          }}
        </span>
        <a-input
          v-show="titleModifiable"
          v-model="tmpTitle"
          style="width: 100px;"
          @keyup.enter="inputToLabel"
          @blur="blur"
        >
        </a-input>
      </div>
      <div class="modal-content">
        <a-row>
          <a-col :span="5">
            <div class="window-left">
              <div style="font-weight: 600;">
                <div class="window-left-menubar">
                  组件列表
                </div>
                <div class="window-left-graphs">
                  <a-row>
                    <a-col :span="5">
                      <div
                        v-for="(vis, index) in visComponentClasses"
                        :key="index"
                      >
                        <div
                          class="window-left-buttons"
                          @click="selectGraphCategory(vis.title)"
                        >
                          <img
                            class="left-icon"
                            :src="
                              publicPath +
                              vis.iconCharCode +
                              `${
                                selectedGraphCategory === vis.title
                                  ? '-active'
                                  : ''
                              }` +
                              '.svg'
                            "
                          />
                        </div>
                      </div>
                    </a-col>
                    <a-col :span="19">
                      <div class="window-content">
                        <div
                          v-for="(graph, index) in graphsCanBeSelected"
                          :key="index"
                          class="graph-box"
                          :class="{
                            'graph-selected': currentGraph === graph.name,
                          }"
                          @click="selectGraph(graph.name)"
                        >
                          <div class="window-content-graph">
                            <span style="color: #5d637e; margin: 6px;"
                              >{{ graph.title }}
                            </span>
                          </div>
                          <div class="window-content-imgs">
                            <img
                              :src="`${publicPath}${graph.imgSrc}`"
                              style="width: 100%;"
                            />
                          </div>
                        </div>
                      </div>
                    </a-col>
                  </a-row>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :span="13">
            <div class="window-middle">
              <div class="window-middle-canvas">
                <Chart
                  v-if="chartVisible"
                  :chart-type="currentGraph"
                  :config="currentGridItem.chartOptions"
                ></Chart>
                <div v-else class="empty-info-box">
                  <img :src="currentChartEmptyImg" />
                  <div class="empty-info">请先配置数据</div>
                </div>
              </div>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="window-right">
              <window-side-bar
                ref="windowSidebar"
                :chart-type="currentGraph"
                @change="onchange"
              />
            </div>
          </a-col>
        </a-row>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import DataViewStore from '@/store/modules/dataview'
import { Watch } from 'vue-property-decorator'
import { saveWidget, updateWidget } from '@/api/right-drawer'
import Chart from '@/components/chart/chart.vue'
import WindowSideBar from '@/components/studio/data/drawer/WindowSideBar.vue'
import { getWidgetJson } from '@/config/setting-chart'
import { publicPath } from '@/api/constants'

@Component({
  components: { Chart, WindowSideBar },
})
export default class VisualWindow extends Vue {
  @Watch('currentGraph')
  public watchCurrentGraph() {
    if (!this.tag) {
      this.title = this.currentGraph
    }
    if (this.currentGraph !== 'donutChart') {
      delete this.currentGridItem.chartOptions.innerRadius
      delete this.currentGridItem.chartOptions.labelPositionMod
    }
  }

  private publicPath = publicPath // 基础URL
  private widgetId: number = -1
  private tag = false // 标记当前窗口是新建窗口还是编辑窗口，false为新建，true为编辑
  private titleModifiable = false
  private tmpTitle = 'barChart' // 重命名时暂存的标题
  private title = 'barChart'
  private currentGridItem: any = null // 当前需要渲染的chart的一些配置信息
  private dataset: any = []
  private datasetColumns: any = []
  private icons = [
    'bar-chart',
    'line-chart',
    'dot-chart',
    'area-chart',
    'stock',
    'heat-map',
    'pie-chart',
    'map-chart',
  ]
  private selectedGraphCategory = 'bar-chart' // 右侧选中的图的类别
  private currentGraph = 'barChart' // 当前选中的图
  private visComponentClasses = {
    BarChart: { title: 'bar-chart', iconCharCode: '/icon/BarChartbeifen' },
    PieChart: { title: 'pie-chart', iconCharCode: '/icon/bingtu' },
    HeatmapMatrix: {
      title: 'heat-map',
      iconCharCode: '/icon/MatrixCopybeifen',
    },
    ParallelCoordinates: { title: 'stock', iconCharCode: '/icon/tuodong' },
    LineChart: { title: 'line-chart', iconCharCode: '/icon/LineChartbeifen' },
    AreaChart: { title: 'area-chart', iconCharCode: '/icon/mianjitu' },
    Scatterplot: {
      title: 'dot-chart',
      iconCharCode: '/icon/Scatterplotbeifen',
    },
    GeographicMap: { title: 'map-chart', iconCharCode: '/icon/map' },
  }

  // 当前类别的图下面可以选择的具体图
  private graphsCanBeSelected: any = [
    {
      name: 'barChart',
      title: '柱状图',
      chartType: 'barChart',
      imgSrc: '/icon/components/barChart.png',
    },
    {
      name: 'groupBarChart',
      title: '分组柱状图',
      chartType: 'barChart',
      imgSrc: '/icon/components/groupBarChart.png',
    },
    {
      name: 'stackBarChart',
      title: '堆栈柱状图',
      chartType: 'barChart',
      imgSrc: '/icon/components/stackBarChart.png',
    },
  ]

  private allGraphs: any = {
    'bar-chart': [
      {
        name: 'barChart',
        title: '柱状图',
        chartType: 'barChart',
        imgSrc: '/icon/components/barChart.png',
      },
      {
        name: 'groupBarChart',
        title: '分组柱状图',
        chartType: 'barChart',
        imgSrc: '/icon/components/groupBarChart.png',
      },
      {
        name: 'stackBarChart',
        title: '堆栈柱状图',
        chartType: 'barChart',
        imgSrc: '/icon/components/stackBarChart.png',
      },
    ],
    'pie-chart': [
      {
        name: 'pieChart',
        title: '饼图',
        chartType: 'pieChart',
        imgSrc: '/icon/components/pieChart.png',
      },
      {
        name: 'donutChart',
        title: '圆环图',
        chartType: 'pieChart',
        imgSrc: '/icon/components/donutChart.png',
      },
    ],
    'line-chart': [
      {
        name: 'lineChart',
        title: '折线图',
        chartType: 'lineChart',
        imgSrc: '/icon/components/lineChart.png',
      },
    ],
    'dot-chart': [
      {
        name: 'scatterplot',
        title: '散点图',
        chartType: 'scatterplot',
        imgSrc: '/icon/components/scatterplot.png',
      },
    ],
    'area-chart': [
      {
        name: 'areaChart',
        title: '面积图',
        chartType: 'areaChart',
        imgSrc: '/icon/components/areaChart.png',
      },
    ],
    stock: [
      {
        name: 'parallelCoordinates',
        title: '平行坐标轴',
        chartType: 'parallelCoordinates',
        imgSrc: '/icon/components/parallelCoordinates.png',
      },
    ],
    'heat-map': [
      {
        name: 'heatmapMatrix',
        title: '热力图',
        chartType: 'heatmapMatrix',
        imgSrc: '/icon/components/heatmapMatrix.png',
      },
    ],
    'map-chart': [
      {
        name: 'geographicMap',
        title: '地图',
        chartType: 'geographicMap',
        imgSrc: '/icon/components/map.png',
      },
    ],
  }

  setTitleModifiable() {
    this.titleModifiable = true
  }

  // 保存重命名
  inputToLabel() {
    this.title = this.tmpTitle
    this.titleModifiable = false
  }

  // 根据选择的图类别重置可选择图
  @Watch('selectedGraphCategory')
  public updateGraphs() {
    this.graphsCanBeSelected = [...this.allGraphs[this.selectedGraphCategory]]
    if (!DataViewStore.getOldItems) {
      this.currentGraph = (this.graphsCanBeSelected[0] as any).name
    }
  }

  public selectGraphCategory(graphCategory: string) {
    this.selectedGraphCategory = graphCategory
  }

  public selectGraph(graph: any) {
    this.currentGraph = graph
  }

  // 获取当前图表默认背景图片
  public get currentChartEmptyImg() {
    const currentChart = this.graphsCanBeSelected.filter(
      (item: any) => item.name === this.currentGraph
    )[0]
    if (currentChart) {
      return this.publicPath + currentChart.imgSrc
    }
    return ''
  }

  public get visible() {
    return DataViewStore.getVisualWindowShow
  }

  private async saveVisual(postData: any) {
    const response = await saveWidget(postData)
    return response
  }

  public get selectNode(): any {
    return DataViewStore.selectNode
  }

  // 保存或者更新
  public handleOk() {
    this.currentGridItem.chartType = [this.currentGraph, this.currentGraph]
    const postData = this.buildSaveParameters(this.currentGridItem)
    if (this.tag) {
      postData.data.id = this.widgetId
      updateWidget(postData).then((response) => {
        if (response.data.code === 100) {
          DataViewStore.setVisualWindowShow(false)
        }
      })
    } else {
      saveWidget(postData).then((response) => {
        if (response.data.code === 100) {
          DataViewStore.setVisualWindowShow(false)
        }
      })
    }
    this.tag = false
  }

  public handleCancel() {
    DataViewStore.setVisualWindowShow(false)
    this.empty()
  }

  public get datasetName() {
    return DataViewStore.getDatasetName
  }

  public empty() {
    this.currentGridItem = {}
  }

  public onchange(item: any) {
    this.currentGridItem = {
      ...item,
    }
    this.tmpTitle = item.chartOptions.title
    if (this.currentGraph === 'stackBarChart') {
      // 不同图表类型下的额外配置，后续增加建议抽成独立的配置
      this.currentGridItem.chartOptions.barIsStack = true
    }
    if (this.currentGridItem.chartOptions.labelIsShow === undefined) {
      this.currentGridItem.chartOptions.labelIsShow = false
    }
    this.currentGridItem.chartOptions.size = [550, 400] // chart 大小
    this.currentGridItem.chartOptions = {
      ...this.currentGridItem.chartOptions,
      xAxisFontSize: 12,
      xAxisFontColor: '#373B52',
      yAxisFontColor: '#373B52',
      xAxisLineColor: '#e9e9e9',
      xAxisLineWidth: 1,
      yAxisLineColor: '#e9e9e9',
      xAxisGridColor: '#e9e9e9',
      yAxisGridColor: '#e9e9e9',
      xAxisTickColor: '#e9e9e9',
      yAxisTickColor: '#e9e9e9',
    }
  }

  // 生成save接口需要的数据
  public buildSaveParameters(gridItem: any) {
    const query = gridItem.dataQuery ? gridItem.dataQuery : {}
    const chartConfig = JSON.parse(JSON.stringify(gridItem.chartOptions))
    gridItem.formData.value = []
    chartConfig.value = []
    const result = {
      data: {
        id: gridItem.widgetId,
        // 'randomId': Math.floor(Math.random()* 10000),
        name: gridItem.chartOptions.title || this.title,
        tid: this.selectNode.id,
        type: 'task',
        data: {
          formData: gridItem.formData,
          widgetJson: query.data
            ? query.data.widgetJson
            : getWidgetJson(gridItem.formData),
          chartType: gridItem.chartType,
          x: gridItem.x,
          y: gridItem.y,
          w: gridItem.w,
          h: gridItem.h,
          i: gridItem.i,
          chartOptions: chartConfig,
        },
      },
    }
    return result
  }

  get chartVisible() {
    if (this.currentGridItem) {
      return true
    }
    return false
  }

  blur() {
    this.titleModifiable = false
    this.title = this.tmpTitle
    this.$set(this.currentGridItem, 'chartOptions', {
      ...this.currentGridItem.chartOptions,
      title: this.tmpTitle,
    })
    this.$set(this.currentGridItem, 'formData', {
      ...this.currentGridItem.chartOptions,
      title: this.tmpTitle,
    })
    // @ts-ignore
    this.$refs.windowSidebar.updateFormTitle(this.tmpTitle)
  }

  public created() {
    if (DataViewStore.getOldItems) {
      const oldItems = DataViewStore.getOldItems
      this.tag = true
      this.currentGraph = oldItems.chartType
      const index = Object.values(this.allGraphs).findIndex((category: any) =>
        category.some((item: any) => item.name === oldItems.chartType)
      )
      this.selectedGraphCategory = Object.keys(this.allGraphs)[index]
      this.title = oldItems.name
      this.tmpTitle = this.title
      this.widgetId = oldItems.widgetId
    }
  }
}
</script>

<style lang="less" scoped>
.modal-content {
  background-color: #fff;
  height: 480px;
  margin: -24px;
  margin-top: 10px;
}

.content-text {
  color: #5d637e;
}

.graph-box {
  background-color: #fff;
  border: 1px solid;
  border-color: #e0e0e0;
  height: 100px;
  margin-top: 10px;
  width: 174px;
}

.graph-selected {
  border-color: #00f;
}

.window-title {
  display: inline-block;
  font-size: 120%;
  font-weight: 600;
  height: 32px;
}

.window-left {
  border: 1px solid #e0e0e0;
  border-bottom: 0;
  height: 480px;
}

.window-left-menubar {
  color: #5d637e;
  margin: 12px;
}

.window-left-graphs {
  border-top: 1px solid;
  border-top-color: #e0e0e0;
  height: 430px;
  width: 100%;
}

.window-left-buttons {
  background-color: #fff;
  border: 0;
  font-size: 25px;
  height: 45px;
  padding: 0 10px;
  width: 45px;

  .left-icon {
    width: 100%;
  }

  &:hover {
    background-color: fade(#f0f3ff, 50%);
    color: fade(#f9f9fc, 50%);
  }

  &:focus {
    background-color: fade(#5561ff, 15%);
    color: fade(#5561ff, 15%);
  }
}

.window-content {
  border-left: 1px solid;
  border-left-color: #e0e0e0;
  height: 430px;
  padding: 5px;
}

.window-content-graph {
  background-color: #f0f3ff;
  height: 26px;
}

.window-content-imgs {
  font-size: 20px;
  height: 70px;
  margin-left: 5px;
  margin-top: -5px;
  width: 160px;
}

.window-middle {
  background-color: #f6f6f6;
  border-top: 1px solid #e0e0e0;
  height: 480px;
}

.window-middle-canvas {
  background-color: #fff;
  height: 420px;
  margin: 30px;
  overflow: hidden;

  .empty-info-box {
    height: 100%;
    text-align: center;

    img {
      margin-top: 50px;
      width: 80%;
    }
  }

  .empty-info {
    color: #999;
    position: relative;
  }
}

.window-right {
  border: 1px solid;
  border-color: #e0e0e0;
  height: 480px;
  overflow-y: scroll;
}
</style>
